import React, { useState } from 'react';
import { Form, Collapse, Icon, Table, Input, Col } from 'antd';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
// import FunctionDescribe from '@/components/NewFunction/FunctionDescribe';
import { useRequest } from '@/hooks';
import { getQueryBusinessData } from '@/pages/WorkFlow/services';
import { withRouter } from 'umi';
import { GRADE, NEWAUTH } from '@/pages/Organization/OrgFlow/constant';
import { GroupLabel } from '@/pages/Setting/Privilege/components/TreeSelectGroupRoleForPrivilege';
import Difference from '@/pages/WorkFlow/components/FormControls/components/Difference';
import { fetchManageList } from '@/pages/Setting/Privilege/services';
import { tree2array } from '@/utils/tree';
import styles from './index.less';
import { findHighestFunctionGrade } from '../NewFunction/utils';

const LabelValue = ({ label, value, children }) => (
    <div className={styles.labelAndValueWrapper}>
        <Col span={4}>
            <div style={{ textAlign: 'right' }}>{label}：</div>
        </Col>
        <Col span={12}>
            {value ? (
                <span
                    // eslint-disable-next-line react/no-danger
                    dangerouslySetInnerHTML={{
                        __html: value && value.replace(/[\r\n]+/g, '<br />')
                    }}
                />
            ) : null}
            <div style={{ display: 'inline-block', minWidth: 120 }}>{children}</div>
        </Col>
    </div>
);
// 获取功能数据，用于摘要显示
const getBusinessInfo = (data = []) => {
    const nameArr = [];
    tree2array(data).map((item, index) => {
        if (index < 10) {
            nameArr.push(`${item.oldBusinessData.constData.nameZh}-${NEWAUTH[item.oldBusinessData.constData.type]}`);
        }
        return '';
    });
    if (data.length > 10) {
        nameArr.push('...');
    }
    return nameArr.join('、');
};

// 对树的数据，进行清空空节点，以及计算tips差异化
const getBusinessTips = data =>
    data.map(item => {
        const result = { ...item };
        const { children, compareDataField, oldBusinessData } = result;
        if (Array.isArray(children) && children.length) {
            result.children = getBusinessTips(children);
        } else {
            delete result.children;
        }
        const tips = {};
        if (compareDataField?.updateFieldNames) {
            compareDataField.updateFieldNames.forEach(v => {
                tips[v] = oldBusinessData[v];
            });
        }
        result.tips = tips;
        return result;
    });

const FunctionManagement = ({ dataSource, form, formValueMap = {}, location }) => {
    const { getFieldDecorator } = form;
    const { children: list = [] } = dataSource;
    const hiDataId = location?.query?.hiDataId || formValueMap?.hiDataId;

    const [businessData, setBusinessData] = useState([]);

    const [tempData, setTempData] = useState();
    const { data: manageList } = useRequest(fetchManageList);
    const [expandAllRows, setExpandAllRows] = useState([]); // 展开项控制

    useRequest(() => getQueryBusinessData(hiDataId), {
        refreshDeps: [hiDataId],
        ready: !!hiDataId,
        onSuccess: v => {
            const { code, data } = v;
            if (code === 10000) {
                setExpandAllRows(data.map(item => item.resourceCode));
                setBusinessData(getBusinessTips(data));
            }
        }
    });
    // 详情页的时候，这两字段需要展示结果，但是三元会出现eslint报错，所以提取出来写这里
    const renderText = type => {
        if (tempData) {
            const { oldBusinessData, functionGrade, isEnable } = tempData;
            const { constData } = oldBusinessData;
            if (type === 'isEnable') {
                return <span>{isEnable ? '开启' : '禁用'}</span>;
            }
            if (type === 'functionGrade') {
                return <span>{functionGrade ? GRADE[functionGrade] : '-'}</span>;
            }
            if (type === 'terminalScope') {
                const tArr = [];
                if (constData.terminalScope.WEB === 1) {
                    tArr.push('Web端');
                }
                if (constData.terminalScope.APP === 1) {
                    tArr.push('App端');
                }
                if (constData.terminalScope.PC === 1) {
                    tArr.push('PC端');
                }
                return tArr.join('、');
            }
            return '';
        }
        return '';
    };
    const columns = [
        {
            title: '功能',
            dataIndex: 'nameZh',
            key: 'nameZh',
            render: (_, record) => {
                const { nameZh } = record?.oldBusinessData?.constData;
                return nameZh;
            }
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            render: (_, record) => {
                const { type } = record?.oldBusinessData?.constData;
                return NEWAUTH[type];
            }
        },
        {
            title: '状态',
            dataIndex: 'isEnable',
            key: 'isEnable',
            render: (value, record) => {
                const { isEnable: oldIsEnable } = record?.tips;
                const { isEnable: newIsEnable } = record;
                return (
                    <Difference
                        tip={
                            // eslint-disable-next-line no-nested-ternary
                            oldIsEnable !== '' && oldIsEnable !== undefined
                                ? oldIsEnable
                                    ? '禁用'
                                    : '开启'
                                : undefined
                        }
                    >
                        <div style={{ padding: '0 10px', minWidth: 100 }}>{newIsEnable ? '开启' : '禁用'}</div>
                    </Difference>
                );
            }
        },
        {
            title: '等级',
            dataIndex: 'functionGrade',
            key: 'functionGrade',
            render: (_, record) => {
                const { functionGrade: oldFunctionGrade } = record?.tips;
                const { functionGrade: newFunctionGrade } = record;
                return (
                    <Difference tip={oldFunctionGrade !== undefined ? GRADE[oldFunctionGrade] : undefined}>
                        <div style={{ padding: '0 10px', minWidth: 100 }}>{GRADE[newFunctionGrade]}</div>
                    </Difference>
                );
            }
        },
        {
            title: () => (
                <div className={styles.newFunctionTableHeader}>
                    <div>业务端实现情况</div>
                    <ul>
                        <li>Web端</li>
                        <li>APP端</li>
                        <li>PC端</li>
                    </ul>
                </div>
            ),
            dataIndex: 'terminalScope',
            key: 'terminalScope',
            width: 200,
            render: (_, record) => {
                const { WEB, APP, PC } = record?.oldBusinessData?.constData.terminalScope;
                return (
                    <div className={styles.functionIncidenceWrapper}>
                        {WEB ? <Icon type="check" /> : <Icon type="minus" />}
                        {APP ? <Icon type="check" /> : <Icon type="minus" />}
                        {PC ? <Icon type="check" /> : <Icon type="minus" />}
                    </div>
                );
            }
        },
        {
            title: '授权模板',
            dataIndex: 'roleCodes',
            key: 'roleCodes',
            render: (value, record) => {
                const { roleCodes: oldRoleCodes } = record?.oldBusinessData;
                const { roleCodes: newRoleCodes } = record;
                return (
                    <GroupLabel
                        title="授权模板"
                        data={manageList?.data || []}
                        value={newRoleCodes}
                        oldValue={oldRoleCodes}
                    />
                );
            }
        }
    ];

    // 这里判断单挑数据还是多条数据的审批
    const numberType = React.useMemo(() => {
        if (tree2array(businessData).length === 1) {
            setTempData({ ...businessData[0] });
            return 'single';
        }
        if (tree2array(businessData).length > 1) {
            return 'multiple';
        }
        return '';
    }, [businessData]);

    return (
        <React.Fragment>
            <div className={styles.newFunctionWrapper}>
                <Collapse
                    defaultActiveKey={['1', '2', '3']}
                    className={styles.collapsePanel}
                    bordered={false}
                    expandIconPosition="right"
                    expandIcon={panelProps => {
                        const { isActive } = panelProps;
                        return (
                            <div className={styles.collapseExpandIcon}>
                                {isActive ? '收起' : '展开'}
                                {isActive ? <Icon type="caret-up" /> : <Icon type="caret-down" />}
                            </div>
                        );
                    }}
                >
                    <Collapse.Panel header="申请原因" key="1">
                        <div className={styles.functionApplyReason}>
                            {Array.isArray(list) &&
                                list.map(item => {
                                    const { label, formId, rules, extra } = item;
                                    let { initialValue } = item;

                                    if (formId === 'functionName') {
                                        initialValue = getBusinessInfo(businessData);
                                    }
                                    if (formId === 'functionGrade') {
                                        initialValue = findHighestFunctionGrade(businessData || []);
                                    }
                                    return (
                                        <Form.Item
                                            label={label}
                                            key={formId}
                                            extra={extra}
                                            style={{ display: item?.inRenderDom === false ? 'none' : 'block' }}
                                        >
                                            {getFieldDecorator(formId, {
                                                initialValue,
                                                rules
                                            })(<AutoRenderComponent form={form} config={item} />)}
                                        </Form.Item>
                                    );
                                })}
                        </div>
                    </Collapse.Panel>
                    {numberType === 'single' ? (
                        <Collapse.Panel header="功能详情" key="2">
                            <div className={styles.functionDescribeList}>
                                <LabelValue
                                    label="功能中文名称"
                                    value={tempData?.oldBusinessData?.constData.nameZh || '-'}
                                />
                                <LabelValue
                                    label="功能英文名称"
                                    value={tempData?.oldBusinessData?.constData.nameEn || '-'}
                                />
                                <LabelValue
                                    label="功能类型"
                                    value={NEWAUTH[tempData?.oldBusinessData?.constData.type] || '-'}
                                />
                                <LabelValue
                                    label="从属功能"
                                    value={tempData?.oldBusinessData?.constData.parentNameZh || '-'}
                                />
                                <LabelValue
                                    label="模块简介（中文）"
                                    value={tempData?.oldBusinessData?.constData.remarkZh || '-'}
                                />
                                <LabelValue
                                    label="模块简介（英文）"
                                    value={tempData?.oldBusinessData?.constData.remarkEn || '-'}
                                />
                                <LabelValue label="业务端实现情况" value={renderText('terminalScope')} />
                                <LabelValue label="状态">
                                    <Difference
                                        tip={
                                            // eslint-disable-next-line no-nested-ternary
                                            tempData?.tips.isEnable !== undefined
                                                ? tempData?.tips.isEnable
                                                    ? '开启'
                                                    : '禁用'
                                                : undefined
                                        }
                                    >
                                        <div style={{ padding: '0 8px' }}>{renderText('isEnable')}</div>
                                    </Difference>
                                </LabelValue>
                                <LabelValue label="功能等级">
                                    <Difference
                                        tip={
                                            tempData?.tips.functionGrade !== '' &&
                                            tempData?.tips.functionGrade !== undefined
                                                ? GRADE[tempData?.tips.functionGrade]
                                                : undefined
                                        }
                                    >
                                        <div style={{ padding: '0 8px' }}>{renderText('functionGrade')}</div>
                                    </Difference>
                                </LabelValue>
                                <LabelValue label="授权模板">
                                    <GroupLabel
                                        placeholder="请选择授权模板"
                                        title="授权模板"
                                        autoFetchData
                                        // data={[]}
                                        value={tempData?.roleCodes}
                                        oldValue={tempData?.oldBusinessData?.roleCodes}
                                    />
                                </LabelValue>
                            </div>
                        </Collapse.Panel>
                    ) : null}
                    {numberType === 'multiple' ? (
                        <Collapse.Panel header="功能信息" key="3">
                            <div className={styles.functionList}>
                                <Table
                                    expandedRowKeys={expandAllRows}
                                    onExpandedRowsChange={e => {
                                        setExpandAllRows(e);
                                    }}
                                    rowKey="resourceCode"
                                    className={styles.functionListTable}
                                    columns={columns}
                                    pagination={false}
                                    dataSource={businessData}
                                    expandIcon={({ expanded, onExpand, record }) => {
                                        const { children } = record;
                                        if (!children) {
                                            return <span style={{ width: 14, height: 14 }}></span>;
                                        }
                                        return expanded ? (
                                            <Icon
                                                type="caret-right"
                                                style={{ marginRight: 5 }}
                                                onClick={e => onExpand(record, e)}
                                            />
                                        ) : (
                                            <Icon
                                                type="caret-down"
                                                style={{ marginRight: 5 }}
                                                onClick={e => onExpand(record, e)}
                                            />
                                        );
                                    }}
                                />
                            </div>
                        </Collapse.Panel>
                    ) : null}
                </Collapse>
                <Form.Item style={{ display: 'none' }}>
                    {getFieldDecorator('hiDataId', {
                        initialValue: hiDataId
                    })(<Input />)}
                </Form.Item>
            </div>
            <br />
        </React.Fragment>
    );
};
export default withRouter(FunctionManagement);
